package gofish.servlets;

import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;

import gofish.dao.DAOException;
import gofish.dao.GoFishDAOHandler;
import gofish.json.JsonObject;
import gofish.objects.Game;

/**
 * GetGameState will be a Servlet that Adam's client code can contact. Adam's
 * code will contact this Servlet when the client realizes (due to a refresh()
 * call) that he/she needs to update their game state.
 * 
 * @author Matt Lauber
 */
public class GetGameState extends HttpServlet {

	/**
	 * doPost() is called by the client when they need to get the latest game
	 * state information. This will return to the client as a JSON the game
	 * state in this format:
	 * 
	 * { "player" : { "hand" : ["5H", "6D", etc], "pairs" : ["4", "Q", etc], },
	 * "opponents" : [ { "name" : string playerName, "hand" : int numberOfCards,
	 * "pairs" : ["2", "K", etc], }, { "name" : string playerName, "hand" : int
	 * numberOfCards, "pairs" : ["2", "K", etc], }, etc ], "turn" : string
	 * playerName, "winners" : [ string playerName, string playerName, etc ] }
	 * 
	 * NOTE: the "winners" array is only added on if the game is over.
	 * 
	 * Notice that the JsonObject class is overloaded to take care of all the
	 * JSON encoding.
	 */
	@Override
	// public void doPost(int gid, String userName) {
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		response.setContentType("application/json");

		PrintWriter out = response.getWriter();
		try {

		JsonObject jsonResponse = new JsonObject();
			String userName = request.getParameter("userName");
			int gid = Integer.parseInt(request.getParameter("gid"));

			GoFishDAOHandler handler = new GoFishDAOHandler(getServletContext());
			Game game = handler.getGameState(gid); // edit JsonObject to get the
													// Game object!!!!

			// Game game = GameData.getGameState(gid); // will change!
			jsonResponse = new JsonObject(handler, game, userName);
			// System.out.println(response);
		// return game;
		out.print(jsonResponse.toString());
		} catch (Exception e) {
			JsonObject json = new JsonObject();
			StringBuilder builder = new StringBuilder();
			for (StackTraceElement elem : e.getStackTrace()) {
				builder.append(elem.toString() + " ");
			}
			json.add("error", builder.toString());
			out.print(json.toString());
		}
		out.flush();
	}

}
